/**
 * 
 */
package org.softTank.BpelTranslator.Impl;

import java.util.List;

import net.sf.json.JSONObject;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Namespace;
import org.dom4j.QName;
import org.softTank.BcpModel.BcpAssign;
import org.softTank.BpelTranslator.StructParser;

/**
 * @author Yuzone
 * 
 */
public class StructParserImpl implements StructParser {

	private int count = 0;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.softTank.BpelTranslator.StructParser#createStructDefinition(java.
	 * lang.String, java.util.List)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public String createStructDefinition(String code, List<BcpAssign> value)
			throws Exception {
		Document doc = DocumentHelper.parseText(code);
		Element root = doc.getRootElement();
		Element rootAssign = ((Element) root.elements().get(
				root.elements().size() - 1)).element("assign");
		List copies = rootAssign.elements("copy");
		if (copies != null) {
			for (Object o : copies) {
				Element copy = (Element) o;
				Element from = copy.element("from");
				Element to = copy.element("to");
				String var = to.attributeValue("variable");
				if (from.element("literal") != null) {
					from.element("literal").addElement(
							createElement(var, value)).addElement(
							createParameter(var, value));
				}
			}
		}

		return doc.asXML();
	}

	private QName createParameter(String variable, List<BcpAssign> value) {
		JSONObject struct = findStruct(variable, value);
		if (struct != null)
			return new QName(struct.getString("parameter"), new Namespace("sns"
					+ count, struct.getString("namespace")));
		return DocumentHelper.createQName("error");
	}

	private QName createElement(String variable, List<BcpAssign> value) {
		JSONObject struct = findStruct(variable, value);
		if (struct != null) {
			count++;
			return new QName(struct.getString("element"), new Namespace("sns"
					+ count, struct.getString("namespace")));
		}
		return DocumentHelper.createQName("error");
	}

	private JSONObject findStruct(String variable, List<BcpAssign> value) {
		if (value != null) {
			for (BcpAssign ba : value) {
				JSONObject jo = JSONObject.fromObject(ba.getTowards());
				if (jo.getString("variable").equalsIgnoreCase(variable))
					return jo;
			}
		}
		return null;
	}

}
